// pages/accessWineGet/accessWineGet.js
const app = getApp();
import {
  getUrlParam,
} from '../../utils/util';
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    id: '',
    deskName: '',
    remark: '',
    order: {
      beid: 0,
      createBy: "",
      createTime: "",
      expireTime: "",
      goodsInfo: [],
      id: 0,
      memberId: 0,
      orderSn: "",
      phone: "",
      remark: "",
      status: 0,
      takeInfo: [],
      updateBy: "",
      updateTime: ""
    },
    isAll: 0,
    submitLock: false,
  },

  //扫桌码
  scanTable() {
    let self = this;
    let tableNum = '';
    wx.scanCode({
      success: (res) => {
        console.log(res);
        try {
          tableNum = getUrlParam('deskCode', res.path);
          self.setData({
            deskName: tableNum,
          });
          wx.showToast({
            title: ' 扫描桌号成功',
            icon: 'success',
            duration: 500
          })
        } catch (e) {
          wx.showToast({
            title: '二维码不正确',
            icon: 'none',
            duration: 1000
          })
        };
      }
    })
  },

  //提示
  showTip() {
    wx.showModal({
      title: '提示',
      content: '上一次提取之后剩余的数量',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //备注改变时
  changeRemark(e) {
    let value = e.detail.value
    this.setData({
      remark: value
    })
  },

  //修改取走数量
  countChange(e) {
    this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum = e.detail.value
    this.setData({
      order: this.data.order,
    })
  },

  //失去焦点时
  countChange2(e) {
    if (e.detail.value < 0) {
      this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum = 0
    }
    if (e.detail.value > this.data.order.goodsInfo[e.currentTarget.dataset.index].leftNum) {
      this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum = this.data.order.goodsInfo[e.currentTarget.dataset.index].leftNum
    }
    this.setData({
      order: this.data.order,
    })
  },

  //减
  onSubGoods(e) {
    if (this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum <= 0) {
      return;
    }
    this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum = this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum - 1
    this.setData({
      order: this.data.order,
    })
  },
  //加
  onAddGoods(e) {
    if (this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum >= this.data.order.goodsInfo[e.currentTarget.dataset.index].leftNum) {
      return;
    }
    this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum = this.data.order.goodsInfo[e.currentTarget.dataset.index].takeNum + 1
    this.setData({
      order: this.data.order,
    })
  },

  //获取订单详情
  getOrderDetail() {
    let that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    let param = {
      id: that.data.id,
    }
    postParamsRequest('/api/vip/wineOrderDetail', param)
      .then(res => {
        console.log("res: ", res.data.data)
        if (res.data.code == 0) {
          res.data.data.goodsInfo.forEach((item, index) => {
            if (that.data.isAll == 1) {
              item.takeNum = item.leftNum;
            } else {
              item.takeNum = 0;
            }
          });
          that.setData({
            order: res.data.data
          })
        }
      })
      .finally(() => {
        wx.hideLoading()
      }).catch((err) => {
        wx.hideLoading()
      });
  },

  //提交
  sureAdd() {
    let that = this;
    if (this.data.submitLock) {
      return;
    }
    if (this.data.deskName == '') {
      wx.showToast({
        title: '请扫描桌台码',
        icon: 'none'
      })
      return;
    }
    let data = {
      beid: app.beid,
      deskName: that.data.deskName,
      remark: that.data.remark,
      takeInfo: that.data.order.goodsInfo,
      takeType: 1,
      wineAccessId: that.data.id,
    };

    let count = 0;
    for (let i = 0; i < data.takeInfo.length; i++) {
      count += data.takeInfo[i].takeNum;
      data.takeInfo[i].accessNum = data.takeInfo[i].leftNum;
      data.takeInfo[i].leftNum = data.takeInfo[i].leftNum - data.takeInfo[i].takeNum
    }

    if (count == 0) {
      wx.showToast({
        title: '至少取走一件',
        icon: 'none'
      })
      return;
    }

    this.setData({
      submitLock: true,
    })
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    postRequest('/api/vip/takeWine', data).then(res => {
      if (res.data.code == 0 && res.data) {
        wx.showToast({
          title: '取走成功',
          icon: 'success',
          mask: true,
        })
        setTimeout(function () {
          wx.navigateBack();
        }, 1000)
      }
      this.setData({
        submitLock: false,
      })
      wx.hideLoading()
    }).catch(err => {
      wx.showModal({
        title: '提示',
        content: err.data.msg || '网络错误',
      })
      console.log('error: ', err)
      this.setData({
        submitLock: false,
      })
      wx.hideLoading()
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id,
        isAll: options.isAll,
      })
      //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
      if (app.token == "" || app.token == undefined) {
        app.initLogin().then(res => {
          this.getOrderDetail();
        }).catch(err => {})
      } else {
        this.getOrderDetail();
      }

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})